package com.yima.baseproj.module.sys.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yima.baseproj.aop.log.Logging;
import com.yima.baseproj.module.config.utils.ResultUtil;
import com.yima.baseproj.module.config.utils.ResultVo;
import com.yima.baseproj.module.sys.kindergarten.KindergartenEntity;
import com.yima.baseproj.module.sys.kindergarten.KindergartenService;
import com.yima.baseproj.module.sys.role.SysRoleEntity;
import com.yima.baseproj.module.sys.role.model.RoleAddOrEditModel;
import com.yima.baseproj.module.sys.user.model.*;
import com.yima.baseproj.module.sys.user.role.SysUserRoleService;
import com.yima.baseproj.config.argument.RequestBodyParam;
import com.yima.baseproj.module.sys.user.model.*;
import com.yima.baseproj.config.exception.type.ApiException;
import com.yima.baseproj.module.config.BaseController;
import com.yima.baseproj.module.config.utils.PageUtil;
import com.yima.baseproj.module.config.utils.PageVo;
import com.yima.baseproj.security.SecurityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.parameters.P;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author 一码
 * @createDate 2023/4/1 09:00
 * @contact 1424529270@qq.com
 */
@Slf4j
@Api(tags = "用户管理")
@RequestMapping("/api/sys/user")
@RestController
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private KindergartenService kindergartenService;

    @PreAuthorize("hasAuthority('sys:user:findAllByPage')")
    @ApiOperation("查询分页")
    @GetMapping("/findAllByPage")
    public Object findAllByPage(PageVo page, UserSearchAddOrEditModel searchModel) {
        Page<Map> pageData = sysUserService.findAllByPage(PageUtil.initMpPage(page),searchModel);
        for (Map record : pageData.getRecords()) {
            //根据user_id 获取role_info列表
            SysRoleEntity roleEntity = sysUserRoleService.getUserRole(record.get("id").toString());
            record.put("roleNameList",Arrays.asList());
            if(ObjectUtil.isNotEmpty(roleEntity)){
                record.put("roleName",roleEntity.getName());
                //获取备注信息
                record.put("remark",roleEntity.getRemark());
            }

            //获取kg_id, 获取幼儿园信息对象
            if(ObjectUtil.isNotEmpty(record.get("kgId"))){
                KindergartenEntity kg = kindergartenService.findById(Integer.parseInt(record.get("kgId").toString()));
                if(ObjectUtil.isNotEmpty(kg)){
                    record.put("kgName",kg.getKgName());
                }
            }

        }
        return pageData;
    }



    @PreAuthorize("hasAuthority('sys:user:findAllByList')")
    @ApiOperation("查询列表")
    @GetMapping("/findAllByList")
    public ResultVo getUser(UserSearchAddOrEditModel searchModel) {
        List<Map> userList = sysUserService.findAllByList(searchModel);
        return ResultUtil.success(userList);
    }


    @Logging(tags = "系统用户管理",value = "添加")
    @PreAuthorize("hasAuthority('sys:user:add')")
    @ApiOperation("添加")
    @PostMapping("/add")
    public void saveUser(@RequestBody @Validated SysUserAddParamModel customAdmin) {
        SysUserEntity sysUser = sysUserService.checkSysUserUnique(customAdmin.getLoginName());
        if(!Objects.isNull(sysUser)){
            throw new ApiException("账号已存在");
        }
        sysUserService.add(customAdmin);
    }

    @Logging(tags = "系统用户管理",value = "修改")
    @PreAuthorize("hasAuthority('sys:user:edit')")
    @ApiOperation("修改")
    @PostMapping("/edit")
    public void revampUser(@RequestBody @Validated SysUserEditParamModel customAdmin) {
        if (getUserId().equals(customAdmin.getId())) {
            throw new ApiException("不可修改自己");
        }
        SysUserEntity sysUser=sysUserService.checkSysUserUnique(customAdmin.getLoginName());
        if(sysUser != null && !customAdmin.getId().equals(sysUser.getId())){
            throw new ApiException("账号已存在，请刷新重试");
        }
        sysUserService.edit(customAdmin);
    }

    @Logging(tags = "系统用户管理",value = "删除")
    @PreAuthorize("hasAuthority('sys:user:delByIds')")
    @ApiOperation("删除")
    @DeleteMapping(value = "/delByIds/{ids}")
    public void delByIds(@PathVariable String[] ids) {
        if (Arrays.asList(ids).contains(SecurityUtil.getUserId())) {
            throw new ApiException("不可删除自己");
        }
        sysUserService.delByIds(ids);
    }

    @ApiOperation("查询首页个人信息")
    @GetMapping("/findProfile")
    public UserProfile findProfile(){
        UserProfile userProfile = sysUserService.getUserProfile(getUserId());
        return userProfile;
    }


    @ApiOperation("根据userid查询用户信息")
    @GetMapping("/findById/{id}")
    public SysUserSelect findById(@PathVariable String id) {
        SysUserSelect sysUser = sysUserService.getUserById(id);
        return sysUser;
    }

    @Logging(tags = "系统用户管理",value = "修改个人信息")
    @ApiOperation("修改个人信息")
    @PostMapping("/edit/profile")
    public void editProfile(@RequestBody @Validated SysUserEditProfileParamModel paramModel) {
        SysUserEntity sysUser = sysUserService.getById(SecurityUtil.getUserId());
        if (!sysUser.getLoginName().equals(paramModel.getLoginName())) {
            SysUserEntity exist = sysUserService.findByLoginName(paramModel.getLoginName());
            if (!Objects.isNull(exist)) {
                throw new ApiException("账号已存在");
            }
        }
        sysUser.setLoginName(paramModel.getLoginName());
        sysUser.setNickName(paramModel.getNickName());
        sysUser.setPhone(paramModel.getPhone());
        sysUser.setHeadUrl(paramModel.getHeadUrl());
        sysUserService.saveOrUpdate(sysUser);
    }

    @Logging(tags = "系统用户管理",value = "用户重置密码")
    @ApiOperation("重置密码")
    @PreAuthorize("hasAuthority('sys:user:rePassword')")
    @PostMapping("/rePassword")
    public String rePassword(@RequestBody @Validated SysUserRePasswordParamModel paramModel) {
        SysUserEntity sysUser = sysUserService.getById(paramModel.getId());
        if (sysUser == null) {
            throw new ApiException("用户不存在，请稍后重试");
        }
        String salt = BCrypt.gensalt();
        String newPassword = "123456";
        sysUser.setPassword(BCrypt.hashpw(newPassword,salt));
        sysUser.setSalt(salt);
        sysUserService.saveOrUpdate(sysUser);

        return newPassword;
    }

    @Logging(tags = "系统用户管理",value = "用户修改密码")
    @ApiOperation("修改密码")
    @PostMapping("/edit/password")
    public void editPassword(@RequestBodyParam(name = "oldPassword") String oldPassword,@RequestBodyParam(name = "newPassword") String newPassword) {
        SysUserEntity sysUser = sysUserService.getById(SecurityUtil.getUserId());
        if (!sysUser.getPassword().equals(BCrypt.hashpw(oldPassword,sysUser.getSalt()))) {
            throw new ApiException("密码不正确");
        }
        String salt = BCrypt.gensalt();
        sysUser.setPassword(BCrypt.hashpw(newPassword,salt));
        sysUser.setSalt(salt);
        sysUserService.saveOrUpdate(sysUser);
    }

    @Logging(tags = "系统用户管理",value = "用户修改头像")
    @ApiOperation("修改头像")
    @PostMapping("/edit/avatar")
    public void editAvatar(@RequestBody CustomAdmin customAdmin) {
        SysUserEntity sysUser = sysUserService.getById(SecurityUtil.getUserId());
        if(sysUser == null){
            throw new ApiException("账号不存在，请刷新重试");
        }
        sysUser.setHeadUrl(customAdmin.getHeadUrl());
        sysUserService.saveOrUpdate(sysUser);
    }




}
